<template>
  <card title="排序">
    <button class="button is-primary" slot="right" @click="finish">完成</button>
    <loading v-if="isLoading"></loading>
    <draggable class="list-group" element="div" v-model="list" :options="dragOptions" v-else> 
      <transition-group type="transition" name="flip-list" tag="div">
        <div class="box" v-for="(item, index) in list" :key="item.id">
          {{index + 1}} - {{item.title}}
          <!-- {{index === lastIds.indexOf(item.id)? '' : ` - 原(${lastIds.indexOf(item.id) + 1})`}} -->
        </div>
      </transition-group>
    </draggable>
  </card>
</template>
<script>
import draggable from 'vuedraggable'
export default {
  name: 'app-sort',
  components: {
    draggable
  },
  computed: {
    dragOptions () {
      return {
        animation: 0,
        group: 'description',
        disabled: !this.editable,
        ghostClass: 'ghost'
      }
    }
  },
  created () {
    let param = {
      page: 1,
      per_page: 10000,
      is_ios: true
    }
    this.isLoading = true
    this.$api.get('ads', param).then(req => {
      this.isLoading = false
      this.list = req.list
      this.lastIds = Array.from(this.list, item => {
        return item.id
      })
    })
  },
  data () {
    return {
      isLoading: false,
      editable: true,
      list: [],
      lastIds: [] // 未排序之前ID的顺序
    }
  },
  methods: {
    finish () {
      let ids = Array.from(this.list, item => {
        return item.id
      })
      this.$api.put('ads/sort_ad', ids).then(() => {
        this.$openMessage({message: '重新排序成功', type: 'success'})
        this.$emit('close')
      }).catch(() => {
        this.$openMessage({message: '重新排序失败'})
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.list-group{
  display: flex;
  flex-direction: column;
  padding: 20px 40px;
  .box {
    cursor: move;
    margin-bottom: 10px;
  }
}
.flip-list-move {
  transition: transform 0.5s;
}
.ghost {
  opacity: .2;
  background: #15b6e4;
  color: white;
}
</style>
